package com.example.dc.utils;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class MailUtils {

    public Integer sendEmail(String toEmail, String subject, String body) {
        // 发送邮箱配置
        final String username = "hswjj2004@163.com";
        final String password = "JRfeqg7Lhc6Skex7";
//        JRfeqg7Lhc6Skex7
        // 邮件配置
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.port", "25");

        // 获取默认的 Session 对象
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            Message message = new MimeMessage(session);

            // 设置发件人
            message.setFrom(new InternetAddress(username));

            // 设置收件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));

            // 设置邮件主题
            message.setSubject(subject);

            // 设置邮件正文
            message.setText(body);

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件已发送成功");

            return 200;
        } catch (MessagingException e) {
            return 404;
        }
    }


}
